package com.example.studentdemo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.studentdemo.constant.RoleConstant;
import com.example.studentdemo.entity.Account;
import com.example.studentdemo.entity.Student;
import com.example.studentdemo.exception.CustomerException;
import com.example.studentdemo.mapper.StudentMapper;
import com.example.studentdemo.service.StudentService;
import com.example.studentdemo.utils.PasswordUtils;
import com.example.studentdemo.utils.TokenUtils;
import com.example.studentdemo.utils.UidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class StudentServiceImpl implements StudentService {

    @Resource
    StudentMapper studentMapper;

    @Override
    public List<Student> selectAll(Student student) {
        return studentMapper.selectAll(student);
    }

    @Override
    public Student selectByUsername(String username) {
        return studentMapper.selectByUsername(username);
    }

    @Override
    public void add(Student student) {
        Student dbStudent = studentMapper.selectByUsername(student.getUsername());
        if (dbStudent != null) {
            throw new CustomerException("账号重复了");
        }

        student.setRole(RoleConstant.STUDENT_ROLE);
        student.setUuid(UidUtils.generateUid());
        if (!StrUtil.isNotBlank(student.getPassword())) {
            student.setPassword(PasswordUtils.encryptPassword("student"));
        }else {
            student.setPassword(PasswordUtils.encryptPassword(student.getPassword()));
        }
        studentMapper.insert(student);
    }

    @Override
    public void register(Student student) {
        this.add(student);
    }

    @Override
    public void update(Student student) {
        studentMapper.updateById(student);
    }

    @Override
    public PageInfo<Student> selectPage(Integer pageNum, Integer pageSize, Student student) {
        PageHelper.startPage(pageNum, pageSize);
        List<Student> studentList = studentMapper.selectAll(student);
        return PageInfo.of(studentList);
    }

    @Override
    public void deleteById(Integer id) {
        studentMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Student> studentList) {
        for (Student student : studentList) {
            this.deleteById(student.getId());
        }
    }

    @Override
    public Student selectById(Integer userId) {
        return studentMapper.selectById(userId);
    }

    @Override
    public Student login(Account account) {
        // 验证账号是否存在
        Student dbStudent = studentMapper.selectByUsername(account.getUsername());
        if (dbStudent == null) {
            throw new CustomerException("账号不存在");
        }
        // 验证密码是否正确
        if (!PasswordUtils.matchesPassword(account.getPassword(), dbStudent.getPassword())) {
            throw new CustomerException("账号或密码错误");
        }
        // 获取设备ID（从account中获取或生成默认值）
        String deviceId = account.getDeviceId();
        if (StrUtil.isBlank(deviceId)) {
            deviceId = "default-device";
        }
        // 创建token并返回给前端
        String token = TokenUtils.createToken(String.valueOf(dbStudent.getId()), "STUDENT", dbStudent.getPassword(), deviceId);
        dbStudent.setToken(token);
        return dbStudent;
    }

    @Override
    public void updatePassword(Account account) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            if (!PasswordUtils.matchesPassword(account.getPassword(), currentUser.getPassword())) {
                throw new CustomerException("500", "原密码输入错误");
            }
            Student dbStudent = studentMapper.selectById(currentUser.getId());
            // 密码更新后，注销该用户的所有登录会话
            TokenUtils.logoutAll(String.valueOf(dbStudent.getId()), "STUDENT");
            dbStudent.setPassword(PasswordUtils.encryptPassword(account.getNewPassword()));
            studentMapper.updateById(dbStudent);
        }
    }
}
